import time

from PySide2 import QtCore
from PySide2.QtCore import Signal
from loguru import logger
import serial
import serial.tools.list_ports


# qmut_1 = QMutex() # 创建线程锁
# 继承QThread
class SerialRunthread(QtCore.QThread):
    #  通过类成员对象定义信号对象
    _signal = Signal(object)
    # 串口对象
    ser = serial.Serial()

    def __init__(self):
        super(SerialRunthread, self).__init__()

    def __del__(self):
        self.wait()

    def run(self):
        # qmut_1.lock()  # 加锁
        logger.info('Runthread1：', "开始线程")
        time.sleep(6)
        try:
            logger.info('Runthread2：', "开始打开串口")
            # Linux open 操作总会卡几秒
            self.ser.open()
            logger.info('Runthread3：', "打开串口中")
            if self.ser.isOpen():
                logger.info('Runthread4：', "串口打开成功")
                self.ser.flushInput()
                logger.info('Runthread5：', "串口数据刷新")
                # self.ser.close()
                # print('mySerial.ser.close')
                # 此后卡一下
                # time.sleep(0.2)
                self._signal.emit(self.ser)  # 注意这里与_signal = pyqtSignal(str)中的类型相同
                # qmut_1.unlock()  # 解锁
            # print('++++MyThread++++')
        except Exception as err:
            logger.info("打开串口错误：", err)
